// action creator with thunking
function createRequest () {
return (dispatch, getState) => {
dispatch({ type: 'REQUEST_STUFF' });
someApiCall(function(response) {
// some processing
dispatch({ type: 'RECEIVE_STUFF' });
});
};
}
function onHandlePress () {
this.props.dispatch({ type: 'SHOW_WAITING_MODAL' });
this.props.dispatch(createRequest());
}
Code is everywhere.
function onHandlePress () {
// createRequest 觸發 action `BEGIN_REQUEST`
this.props.dispatch(createRequest());
}
function *watchBeginRequest() {
yield takeEvery('BEGIN_REQUEST', beginRequest);
}
function beginRequest() {
yield put({ type: 'SHOW_WAITING_MODAL' });
const response = yield call(myApiFunctionThatWrapsFetch);
yield put({ type: 'PRELOAD_IMAGES', response.images });
yield put({ type: 'HIDE_WAITING_MODAL' });
}
所有業務代碼都存於 saga 中,不再散落在各處
全同步執行,就算邏輯在複雜,看起來也不會亂